import 'dart:convert';
import 'dart:io';

import 'package:asmore/library.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:permission_handler/permission_handler.dart';

String format(Duration duration) {
  String str = "";
  // 获取Duration的组成部分
  int hours = duration.inHours;
  int minutes = duration.inMinutes % 60;
  int seconds = duration.inSeconds % 60;

  if (hours > 0) {
    str += "$hours:";
  }

  str += "${padZero(minutes)}:";

  str += padZero(seconds);

  return str;
}

String padZero(int num) {
  if (num > 9) return "$num";
  return "0$num";
}

Image getImage(String path, {double? width, double? height}) {
  if (path == "") {
    return Image.asset(
      "assets/images/cover.png",
      width: width,
      height: height,
      fit: BoxFit.cover,
    );
  }
  return Image.file(
    File(path),
    width: width,
    height: height,
    fit: BoxFit.cover,
  );
}

var cachedWorks = <String, DateTime>{};

Future<void> getWorkInfo(String code, Artwork work) async {
  if (cachedWorks[work.id] != null) {
    print("Cached hit: ${work.id}");
    return;
  }
  var client = http.Client();

  // 创建一个URI对象
  var uri = Uri.parse(
      "https://www.dlsite.com/maniax/product/info/ajax?product_id=$code&cdn_cache_min=1");

  // 发出GET请求
  var request = http.Request('GET', uri);
  request.headers["sec-ch-ua"] =
      "\"Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Microsoft Edge\";v=\"122\"";
  request.headers["sec-ch-ua-platform"] = "\"Windows\"";
  request.headers["x-requested-with"] = "XMLHttpRequest";
  request.headers["Referer"] =
      "https://www.dlsite.com/maniax/work/=/product_id/$code.html";
  var response = await client.send(request);

  // 检查响应状态码
  if (response.statusCode == 200) {
    // 读取响应体
    var responseBody = await response.stream.bytesToString();
    // print('Response body: $responseBody');
    var data = jsonDecode(responseBody);
    work.title = data[code]["work_name"];
    work.price = data[code]["price"];
    work.rate_average_2dp = data[code]["rate_average_2dp"];
    work.maker_id = data[code]["maker_id"];
    work.dl_count = int.parse(data[code]["dl_count"]);
    cachedWorks[work.id] = DateTime.now();
  } else {
    print('Request failed with status ${response.statusCode}');
  }

  // 关闭客户端连接
  client.close();
}

Future<bool> requestPermission() async {
  if (!Platform.isAndroid) return true;
  // You can request multiple permissions at once.
  Map<Permission, PermissionStatus> statuses = await [
    Permission.storage, ////
  ].request();
  var status = await Permission.storage.status;
  if (status.isDenied) {
    // We haven't asked for permission yet or the permission has been denied before, but not permanently.
    return false;
  }
  if (status.isGranted) return true;
  return false;
}
